var app=getApp();
var network = require('../../utils/network.js');
var pageNum=1;//当前页数
var searchTitle=""//搜索关键字
var msgListKey="";//文章列表本地缓存key
Page({
    data: {
        cHistory: [
            { city: '北京' },
            { city: '上海' },
            { city: '武汉' },
            { city: '西安' },
        ],
        iconTop: '22rpx',//聚焦前 放大镜上偏移量
        iconLeft: '300rpx',//聚焦前 放大镜左偏移量
        iptPosition: 'center',//聚焦前 搜索框子元素显示位置
        iptWidth:'637rpx',//聚焦前 搜索框款
        bShow: false, //聚焦前 “取消”不显示
        iShow: false,//聚焦前 小×不显示
        inputValue:'',//搜索框的值
        currentCity: '',//当前城市
        msgList: [], // 存储文章列表信息
        searchLogShowed:true,//历史记录是否显示
        isShowHotCity: true,//是否显示热门城市 默认显示
        isgo: 0,//出发: 0 到达: 1
        currentDepartCityName: '',//当前显示的出发城市
        currentDepartCity: {},//当前显示的出发城市的信息
        searchLogList: [],//查询历史记录列表
        hotCityList: []//热门城市列表
    },
    onLoad: function (options) {
        var that = this;
        that.setData({
            isgo: Number(options.isgo)
        });

        /*wx.setStorageSync("searchCityHistoryList",{
            data: [{
                departCity: {
                  "id": "440300000000",
                  "findname": "深圳市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                },
                reachCity: {
                  "id": "440300000000",
                  "cityname": "长春市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                }
            },{
                departCity: {
                  "id": "440300000000",
                  "findname": "深圳市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                },
                reachCity: {
                  "id": "440300000000",
                  "cityname": "杭州市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                }
            },{
                departCity: {
                  "id": "440300000000",
                  "findname": "长春市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                },
                reachCity: {
                  "id": "440300000000",
                  "cityname": "厦门市",
                  "find_quanpin": "shenzhenshi",
                  "find_jianpin": "szs",
                  "province": "广东省",
                  "displayorder": 440300,
                  "netname": "nmd.bus365.cn",
                  "netaddress": "0.0.0.0",
                  "deptarttype": 1,
                  "owns": []
                }
            }]
        });*/

        var tmpArr = [],
            searchLogArr = [],//历史记录
            searchCityHistoryList = wx.getStorageSync("searchCityHistoryList").data || [],//查询历史记录按“出发地-目的地”为对象进行存储
            departCityInfo = wx.getStorageSync("departCityInfo"),//出发城市信息
            hotCityArr;//热门城市

        if(that.data.isgo == 0) {
            //获取当前的地理位置经纬度信息
            that.getLocation();
            // 出发地历史记录
            for (var i = 0; i < searchCityHistoryList.length; i++) {
                if(searchCityHistoryList[i]) {
                    tmpArr.push(searchCityHistoryList[i].departCity);  
                }
            }
            searchLogArr = that.arrUnique(tmpArr,'findname');

            /**
             * 获取热门城市
             * province: '',//省份
             * rowCount: '',//行数
             * page: ''//页数
             */ 
            that.getHotCity("api_schedule_topdepartcitys", {
                province: departCityInfo.province,//省份
                rowCount: 3,//行数
                page: 1,//页数
                token: network.token
            });
        } else if (that.data.isgo == 1) {
            // 目的地历史记录
            for (var i = 0; i < searchCityHistoryList.length; i++) {
                if(searchCityHistoryList[i]) {
                    tmpArr.push(searchCityHistoryList[i].reachCity);   
                }
            }
            searchLogArr = that.arrUnique(tmpArr,'cityname');

            /**
             * 获取热门城市
             * cityid: '',//出发城市id
             * page: '',//页数
             * size: ''//页大小
             */
            that.getHotCity("api_schedule_reachrecommend", {
                cityid: departCityInfo.id,//出发城市id
                page: 2,//页数
                size: 6//页大小
            });
        }
        that.setData({searchLogList: searchLogArr});

        // 如果缓存中有值，先从缓存中读取
        /*var info = wx.getStorageSync(msgListKey);
        if (info) {
            that.setData({
                msgList: info,
                searchLogShowed:true
            });
        }
        var that = this;
        if ("" != wx.getStorageSync('searchLog')) {
            that.setData({
                searchLogShowed:true,
                searchLogList: wx.getStorageSync('searchLog')
            });
        }
        */

        // wx.request({
        //     url: './gocity.json',
        //     header: {
        //         'content-type': 'application/json' 
        //     },
        //     method:'Get',
        //     dataType:'json',
        //     success: function (res) {
        //         console.log(res.data)
        //     }
        // })
    },
    // 页面初次渲染完成
    onReady: function() {
      console.log(this.data.isgo)
        var titleTxt = this.data.isgo === 0 ? "出发地" : "目的地";
        wx.setNavigationBarTitle({title: titleTxt});
    },
    // 数组对象去重
    arrUnique: function (arr,name) {
        var ret = [];
        var hash = {};
        for (var i = 0; i < arr.length; i++) {
            if(arr[i]) {
                var item = arr[i][name];  
                var key = item;
                if (hash[key] !== 1) {
                    ret.push(arr[i]);
                    hash[key] = 1;
                }
            }
        }
        return ret;
    },
    // 获取热门城市信息
    getHotCity: function(url,obj) {
        var that = this,
            hotCityArr;
        wx.request({
            url: app.getApi(url),
            data: obj,
            header: {
              'content-type': 'application/json'
            },
            success: function(res) {
                hotCityArr = that.data.isgo ? res.data.data : res.data;
                that.setData({hotCityList: hotCityArr});
            }
        });
    },
    // 获取当前的地理位置经纬度信息
    getLocation: function () {
        //获取当前的地理位置经纬度信息
        var that = this;
        wx.getLocation({
            type: 'wgs84', 
            success: function(res) {
                //console.log('获取到的定位信息',res);
                that.locationCity({
                    longitude: res.longitude,
                    latitude: res.latitude
                });
            },
            fail: function(res) {
                // 定位失败后默认城市
                that.setData({currentDepartCity: '获取定位失败'});
            }
        });
    },
    //根据经纬度信息获取定位出发城市的名字，比如北京市
    locationCity: function(obj) {
        var that = this;
        wx.request({
            url: 'https://api.map.baidu.com/geocoder/v2/?ak=OxUmBw5HfbmvmAcSQr1gRMHU&location=' + obj.latitude + ',' + obj.longitude + '&output=json',
            data: {},
            header: {
                'Content-Type': 'application/json'
            },
            success: function (res) {
                //console.log('根据经纬度获取城市信息',res);
                var cityName = res.data.result.addressComponent.city;
                that.setData({currentDepartCity: cityName});
                that.findLocationCity(that.data.currentDepartCity);
            },
            fail: function () {
                that.setData({currentDepartCity: "获取定位失败"});
                that.findLocationCity(that.data.currentDepartCity);
            }
        });
    },
    //根据城市名字获取定位出发城市的信息
    findLocationCity: function(cityName) {
        var that = this;
        wx.request({
            url: app.getApi("api_better_departure"),
            data: {cityname: cityName},
            header: {
                'content-type': 'application/json'
            },
            success: function(res) {
                //console.log('根据城市名获取定位城市信息',res);
                if(res.data.length) {
                    that.setData({currentDepartCity: res.data[0],
                        currentDepartCityName: res.data[0].findname});
                }
            },
            fail: function(res) {
                //console.log('获取定位城市信息失败',res);
            }
        });
    },
    // 保存选中的出发城市或目的地城市的信息
    saveSelectedCity: function(value) {
        var that = this;
        //出发: 0 到达: 1
        if(that.data.isgo == 0) {
            wx.setStorageSync("departCityInfo", value);
        } else if (that.data.isgo == 1) {
            wx.setStorageSync("reachCityInfo", value);
        }
    },
    //选中某个城市时
    backIndex:function(e){
        var that = this,
            tapsrc = e.currentTarget.dataset.tapsrc,
            //1:当前定位 2:历史记录 3:热点城市
            index = e.currentTarget.dataset.index;
        if(tapsrc == 1) {
            that.saveSelectedCity(that.data.currentDepartCity);
        } else if(tapsrc == 2) {
            that.saveSelectedCity(that.data.searchLogList[index]);
        } else if(tapsrc == 3) {
            that.saveSelectedCity(that.data.hotCityList[index]);
        }
        
        wx.navigateBack({
            url: '../index/index?isgo='+ that.data.isgo
        });
    },
    changeStyle:function(e){
        var that=this
        that.setData({
            iconLeft: '16rpx',
            iptPosition: 'left',
            iptWidth: '553rpx',
            bShow: true,
        })
    },
    // backStyle:function(e){
    //     var that = this
    //     that.setData({
    //         iconTop: '22rpx',
    //         iconLeft: '300rpx',
    //         iptPosition: 'center',
    //         iptWidth: '637rpx',
    //         bShow: false,
    //         iShow: false,
    //         inputValue: ''
    //     })
    // },
    
    cancel:function(){
        wx.switchTab({
            url: '../index/index'
        })
    },
    // 失去焦距时将输入内容存入缓存
    searchData:function(){
        var that=this
        that.setData({
            msgList:[],
        })
        if(""!=searchTitle){
            var searchLogData = that.data.searchLogList;
            searchLogData.push(searchTitle);
            wx.setStorageSync('searchLog', searchLogData);
        }
    },
    // 输入内容时 把当前内容赋值给查询的关键字
    inputTyping: function (e) {
        var that = this;
        if (e.detail.value != '') {
            that.setData({
                iShow: true
            })
        }
        console.log(e.detail.value);
        console.log(wx.getStorageSync('searchLog'))
        // 如果不做这个if判断，会导致 searchLogList 的数据类型由 list 变为 字符串
        if ("" != wx.getStorageSync('searchLog')) {
            that.setData({
                inputVal: e.detail.value,
                searchLogList: wx.getStorageSync('searchLog')
            });
            if (e.detail.value != '') { 
                
            }
        } else {
            that.setData({
                inputVal: e.detail.value,
            });
        }
        searchTitle = e.detail.value;
    },
    iconClear: function (e) {
        console.log(1)
        var that = this
        that.setData({
            inputValue: '',
            iShow: false
        })
    },
    // 通过搜索记录查询数据
    searchDataByLog: function (e) {
        searchTitle = e.target.dataset.log;
        var that = this;
        that.setData({
            msgList: [],
            scrollTop: 0,
            searchLogShowed: false,
            inputVal: searchTitle
        });
        pageNum = 1;
        loadMsgData(that);
    }
})    